package auto.app.util;

import auto.app.exetion.MainExection;
import auto.app.vo.TestReportVo;
import cn.hutool.core.util.ObjectUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
import com.itextpdf.text.pdf.draw.LineSeparator;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 生成pdf文件
 */
public class PdfReport {

    // 定义全局的字体静态变量
    private static Font titlefont;
    private static Font headfont;
    private static Font keyfont;
    private static Font textfont;
    private static Font smallheadfont;
    private static Font newsmallheadfont;
    // 最大宽度
    private static int maxWidth = 520;
    // 静态代码块
    static {
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 10, Font.NORMAL);
            smallheadfont=new Font(bfChinese,12,Font.BOLD);
            newsmallheadfont=new Font(bfChinese,10,Font.BOLD);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ByteArrayOutputStream  pdfReportExcult(List<TestReportVo> testReportVoList,String accountName) throws Exception {

        try {
            if(ObjectUtil.isNull(testReportVoList)){
                throw new MainExection(500,"该合集并没有测试报告");
            }
            // 1.新建document对象
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Document document = new Document(PageSize.A4);// 建立一个Document对象
            // 2.建立一个书写器(Writer)与document对象关联
//            File file = new File("C:\\Users\\A\\Desktop\\PDFDemo.pdf");
//            file.createNewFile();
//            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            writer.setPageEvent(new Watermark("AutoApi"));// 水印
            writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("测试报告");// 标题
            document.addAuthor("yangsen199606@163.com");// 作者
            document.addSubject("autoApi");// 主题
            document.addKeywords("Keywords@iTextpdf");// 关键字
            document.addCreator("杨森");// 创建者

            // 4.向文档中添加内容
            new PdfReport().generatePDF(document,testReportVoList,accountName);
            // 5.关闭文档
            document.close();
            return baos;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    // 生成PDF文件
    public void generatePDF(Document document,List<TestReportVo> testReportVoList,String accountName) throws Exception {

        // 段落
        Paragraph paragraph = creatAllTitel("接口自动化测试报告");
        //编写目的标题 及锻炼
        Paragraph paragraphTitle = creatTitle("编写目的:");
        // 段落
        Paragraph paragraphnew = creatDuan("本测试报告为接口自动化测试报告；本报告目的在于总结测试阶段的测试以及测试结果分析，描述系统所提供的各功能点是否达到预期目标；反馈跟踪系统功能实现的缺陷及修复情况；从而提高系统的质量，最终满足客户使用需求。");
        //读者对象标题
        Paragraph paragraphDuZhe = creatTitle("读者对象:");
        //读者对象段落
        Paragraph creatDuan = creatDuan("本文档主要目标读者有：项目各级主管领导、产品经理、设计者、测试人员以及系统维护人员。");

        // 表格
        PdfPTable tableBanben = createTable(new float[] { 40, 120, 40, 120});
        tableBanben.addCell(createCell("版本新修记录", headfont, Element.ALIGN_LEFT, 6, false));
        tableBanben.addCell(createCell("编写人", keyfont, Element.ALIGN_CENTER));
        tableBanben.addCell(createCell("日期", keyfont, Element.ALIGN_CENTER));
        tableBanben.addCell(createCell("版本号", keyfont, Element.ALIGN_CENTER));
        tableBanben.addCell(createCell("备注", keyfont, Element.ALIGN_CENTER));

        tableBanben.addCell(createCell("杨森", textfont));
        tableBanben.addCell(createCell(LocalDateTime.now().toString(), textfont));
        tableBanben.addCell(createCell("V1.0", textfont));
        tableBanben.addCell(createCell("接口自动化生成测试报告", textfont));
        for (int i = 0; i <4 ; i++) {
            tableBanben.addCell(createCell(" ", textfont));
            tableBanben.addCell(createCell(" ", textfont));
            tableBanben.addCell(createCell(" ", textfont));
            tableBanben.addCell(createCell(" ", textfont));
        }


        // 直线
        Paragraph p1 = new Paragraph();
        p1.add(new Chunk(new LineSeparator()));

        // 点线
        Paragraph p2 = new Paragraph();
        p2.add(new Chunk(new DottedLineSeparator()));

        // 超链接
        Anchor anchor = new Anchor("baidu");
        anchor.setReference("www.baidu.com");

        // 定位
        Anchor gotoP = new Anchor("goto");
        gotoP.setReference("#top");

        // 添加图片
//        Image image = Image.getInstance("https://img-blog.csdn.net/20180801174617455?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zNzg0ODcxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70");
//        image.setAlignment(Image.ALIGN_CENTER);
//        image.scalePercent(40); //依照比例缩放

        // 表格
        PdfPTable table = createTable(new float[] { 20, 120, 40, 180,40,30});
        table.addCell(createCell("测试合集执行情况", headfont, Element.ALIGN_LEFT, 6, false));
        table.addCell(createCell("用例ID", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("用例名称", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("执行情况", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("执行结果", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("执行信息", keyfont, Element.ALIGN_CENTER));
        table.addCell(createCell("执行人", keyfont, Element.ALIGN_CENTER));
        Integer totalQuantity = 0;
        AtomicReference<Integer> successTest= new AtomicReference<>(0);
        AtomicReference<Integer> failTest= new AtomicReference<>(0);
        testReportVoList.forEach(testReportVo -> {
            if (testReportVo.getStatus().equals("S")){
                successTest.updateAndGet(v -> v + 1);
            }else {
                failTest.updateAndGet(v -> v + 1);
            }
            table.addCell(createCell(testReportVo.getCaseId().toString(), textfont));
            table.addCell(createCell(testReportVo.getCaseName(), textfont));
            table.addCell(createCell(testReportVo.getStatus(), textfont));
            table.addCell(createCell(testReportVo.getResult(), textfont));
            table.addCell(createCell(testReportVo.getMessage(), textfont));
            if (accountName !=null && !"".equals(accountName)){
                table.addCell(createCell(accountName, textfont));
            }else {
                table.addCell(createCell("定时任务", textfont));
            }
        });
        //读者对象标题
        Paragraph elements = creatTitle("执行总结:");
        //读者对象段落
        Paragraph elements1 = creatDuan("本次共执行"+testReportVoList.size()+"条用例,其中"+successTest+"条成功,"+failTest+"条失败;详细情况见表格");

        document.add(paragraph);
        document.add(tableBanben);
        document.add(paragraphTitle);
        document.add(paragraphnew);
        document.add(paragraphDuZhe);
        document.add(creatDuan);
        document.add(elements);
        document.add(elements1);
        document.add(p1);
        document.add(table);
    }
    //居中标题
    //创建段落
    public Paragraph creatAllTitel(String title){
        Paragraph paragraphnew = new Paragraph(title, titlefont);
        paragraphnew.setAlignment(1); //设置文字居中 0靠左   1，居中     2，靠右
        paragraphnew.setIndentationLeft(12); //设置左缩进
        paragraphnew.setIndentationRight(12); //设置右缩进
        paragraphnew.setFirstLineIndent(24); //设置首行缩进
        paragraphnew.setLeading(20f); //行间距
        paragraphnew.setSpacingBefore(5f); //设置段落上空白
        paragraphnew.setSpacingAfter(10f); //设置段落下空白
        return paragraphnew;
    }
    //创建标题
    public Paragraph creatTitle(String name){
        Paragraph paragraphTitle = new Paragraph(name, headfont);
        paragraphTitle.setAlignment(0); //设置文字居中 0靠左   1，居中     2，靠右
        return paragraphTitle;
    }
    //创建段落
    public Paragraph creatDuan(String duanLuo){
        Paragraph paragraphnew = new Paragraph(duanLuo, textfont);
        paragraphnew.setAlignment(0); //设置文字居中 0靠左   1，居中     2，靠右
        paragraphnew.setIndentationLeft(12); //设置左缩进
        paragraphnew.setIndentationRight(12); //设置右缩进
        paragraphnew.setFirstLineIndent(24); //设置首行缩进
        paragraphnew.setLeading(20f); //行间距
        paragraphnew.setSpacingBefore(5f); //设置段落上空白
        paragraphnew.setSpacingAfter(10f); //设置段落下空白
        return paragraphnew;
    }

    public Image createImage(String url) throws IOException, BadElementException {
        Image image = Image.getInstance("C:\\Users\\A\\Desktop\\img\\"+url);
        image.setAlignment(Image.ALIGN_CENTER);
        image.scalePercent(25); //依照比例缩放
        return image;
    }

    //创建二级标题
    public Paragraph creatTwoTitle(String name){
        Paragraph paragraphTitle = new Paragraph(name, smallheadfont);
        paragraphTitle.setAlignment(0); //设置文字居中 0靠左   1，居中     2，靠右
        return paragraphTitle;
    }

    //创建三级标题
    public Paragraph creatThreeTitle(String name){
        Paragraph paragraphTitle = new Paragraph(name, newsmallheadfont);
        paragraphTitle.setAlignment(0); //设置文字居中 0靠左   1，居中     2，靠右
        return paragraphTitle;
    }


/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     * @param value
     * @param font
     * @return
     */
    public PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平..）
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并、设置单元格内边距）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }
    /**
     * 创建单元格（指定字体、水平..、边框宽度：0表示无边框、内边距）
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/
    /**
     * 创建默认列宽，指定列数、水平(居中、右、左)的表格
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建指定列宽、列数的表格
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建空白的表格
     * @return
     */
    public PdfPTable createBlankTable() {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
}
